<!--
 * @Description: Description
 * @Date: 2022-03-24 21:14:42
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-06-02 17:53:31
 * @FilePath: \daobao-web\src\views\modelInfo\userInfoExt.vue
-->
<template>
    <div>
        <a-modal v-model:visible="modelFlag" :title="modelInfo.id?disableds?'查看':'编辑':'新增'"
            :ok-button-props="{ disabled: disabledButton }" @ok="submit" width="1200px" wrapClassName="full-modal">
            <div class="select-range-time">
            </div>
            <a-row type="flex">
                <a-form ref="ruleForm" style="width:100%;" :label-col="{span:8}" :wrapper-col="{span:20}"
                    :model="modelInfo">
                    <a-row>
                        <a-col :span="12">
                            <a-form-item has-feedback label="名称:" style="width:100%" name="name"
                                :rules="[{ required: true, message: '名称' }]">
                                <a-input v-model:value="modelInfo.name" :disabled="disableds" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item has-feedback label="地址:" style="width:100%" name="addr"
                                :rules="[{ required: true, message: '地址' }]">
                                <a-input v-model:value="modelInfo.addr" :disabled="disableds" />
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="12">
                            <a-form-item has-feedback label="电话:" style="width:100%" name="phone"
                                :rules="[{ required: true, message: '电话' }]">
                                <a-input v-model:value="modelInfo.phone" :disabled="disableds" />
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </a-row>
            <div class="margin-tb-2x">
                <div class="flex">
                    <div>工地作业车辆</div>
                    <a-button size="small" :disabled="disableds" class="margin-left-1x" @click="vehicleList.push({})" type="danger" style="background:aqua;border-color:aqua">新增</a-button>
                </div>
              
                <a-table :columns="columns" :data-source="vehicleList" :rowKey="record=>record.vehicle" bordered
                    :scroll="{ y: 300 }" :pagination="false">
                    <template #bodyCell="{column,record,index}">
                        <template v-if="column.dataIndex=='fleetName'">
                            <a-input v-model:value="record.fleetName" placeholder="车队名称"  :disabled="disableds"  /> 
                        </template>
                        <template v-if="column.dataIndex=='fleetContact'">
                            <a-input v-model:value="record.fleetContact" placeholder="车队联系人"  :disabled="disableds"  /> 
                        </template>
                        <template v-if="column.dataIndex=='plateNumber'">
                            <a-input v-model:value="record.plateNumber" placeholder="车牌号"  :disabled="disableds"  /> 
                        </template>
                        <template v-if="column.dataIndex=='action'">
                            <a-button class="ml10" size="small" @click="vehicleList.splice(index,1)"   :disabled="disableds">
                                    <CloseCircleOutlined  />
                                </a-button>
                        </template>
                    </template>

                </a-table>
            </div>
            <div>
                <div>电子围栏</div>
                <div class="dmapBox">
                    <div class="seharBox">
                        <div>搜索地址</div>
                        <input id="tipinput" />.
                        <a-button class="ml10" size="small" @click="startPolygon" title="绘制电子围栏" :disabled="disableds">
                            <FormOutlined />
                        </a-button>
                        <a-button class="ml10" size="small" title="清空电子围栏" @click="clesoPolygon" :disabled="disableds">
                            <CloseCircleOutlined />
                        </a-button>
                    </div>
                    <div class="dmap" id="dmap">
                    </div>
                </div>
            </div>
            <template #footer>
                <div v-if=" !disableds">
                    <a-button @click="modelFlag=false">取消</a-button>
                    <a-button type="primary" @click="submit">确定</a-button>
                </div>
                <div v-else></div>
            </template>
        </a-modal>

    </div>
</template>

<script setup>
    import {
        EyeOutlined,
        CloseCircleOutlined,
        FormOutlined,
    } from '@ant-design/icons-vue'
    import {
        computed,
        defineComponent,
        reactive, //响应式
        watch, //响应式
        ref,
        onMounted,
        defineEmits,
        defineExpose,
    } from 'vue';
    import {
        message
    } from 'ant-design-vue';
    import {formatDateTime} from "@/utils"

    import store from "@/store"
    import {
        shallowRef
    } from "@vue/reactivity"
    const submitFlag = ref(true)
    const ruleForm = ref(null)
    const emit = defineEmits(["getlist"])
    const
        modelFlag = ref(false),
        disableds = ref(true),
        modelInfo = ref({
            time: []
        })
    const vehicleList = ref([])
    const columns = ref([{
            title: '序号',
            dataIndex: 'statusStr',
            ellipsis: true,
            customRender: (column) => column.index + 1,
        },
        {
            title: '车队名称',
            dataIndex: 'fleetName',
            ellipsis: true,
        },
        {
            title: '车队联系人',
            dataIndex: 'fleetContact',
            ellipsis: true,
        },
        {
            title: '车牌号',
            dataIndex: 'plateNumber',
            ellipsis: true,
        },
     

        {
            title: '操作',
            width:70,
            dataIndex: 'action',
            fixed: "right",
        },
    ])

    const map = computed(() => store.getters.AmapInfo)
    const editModel = async (item,flag) => {
        disableds.value = flag
        modelFlag.value = true
        modelInfo.value = {...item}
        vehicleList.value=item.vehicleList
        if (ruleForm.value) {
            ruleForm.value.clearValidate()
        }
        if(item && item.geoJson){
            getMap(item.geoJson)
        }else{
            getMap()
        }
    }

    const submit = () => {
        if (!submitFlag.value) return
        if (vehicleList.value.length && vehicleList.value.some(x => !x.fleetName || !x.plateNumber || !x
                .fleetContact)) {
            return message.error('请填写完车辆信息')
        }
        submitFlag.value = false
        ruleForm.value.validate().then(res => {
            modelInfo.value.siteVehicleMsgDTO = vehicleList.value
            modelInfo.value.geoJson =  [...PolygonListArr.map(k => k.map(x => {
                    return [x.lng, x.lat]
                })), ...overlaysPath.value]

            console.log(modelInfo.value)
    
            return
            if (modelInfo.value.id) {
                updata(modelInfo.value).then((res) => {
                    if (res.status == 200) {
                        modelFlag.value = false
                        message.success('修改成功！')
                        emit("getlist", 1);
                    }
                    submitFlag.value = true
                })
                return;
            }
            add(modelInfo.value).then((res) => {
                if (res.status == 200) {
                    modelFlag.value = false
                    message.success('新增成功！')
                    emit("getlist", 1);
                }
                submitFlag.value = true
            })
        }).catch(err => {
            submitFlag.value = true
            if (err && err.errorFields && err.errorFields.length) {
                message.error('请填写' + err.errorFields[0].errors[0])
            }

        })

    }




    const placeSearch = shallowRef()
    const getMap = ((list) => {
        store.dispatch("map/AmapInit").then((amap) => {
            return amap.init("dmap", {
                    mapStyle: 'amap://styles/darkblue', //设置地图的显示样式
                    rotateEnable: false,
                    pitchEnable: true,
                    resizeEnable: true,
                    zoom: 12,
                    // pitch: 45, //45度俯视
                    // rotation: 45,
                    viewMode: '3D', //type ? '2D' : '3D', //开启3D视图,默认为关闭
                    zooms: [2, 20],
                    skyColor: "#002d56", //天空颜色 倾斜后才会产生
                    center: [121.446395, 31.221499],
                   
                })
        })
        .then(res => {
            res.on("complete", () => {
                const autoOptions = {
                    input: 'tipinput'
                }
                const auto = new AMap.Autocomplete(autoOptions)
                placeSearch.value = new AMap.PlaceSearch({
                    map: res
                }) // 构造地点查询类
                AMap.event.addListener(auto, 'select', select) // 注册监听，当选中某条记录时会触发
            });

            if (list) {
                addPolygon(list)
            }

        })
    })
   
    const select = (e) => {
        placeSearch.value.setCity(e.poi.adcode)
        placeSearch.value.search(e.poi.name) // 关键字查询查询
    }

    var mouseTool = null
    const overlays = ref([])
    const overlaysPath = ref([])
    var PolygonList = []
    var PolygonListArr = []
    const startPolygon = () => {
        mouseTool = new AMap.MouseTool(map.value.amap);
        mouseTool.on('draw', function (e) {
            overlays.value.push(e.obj);
            overlaysPath.value.push(e.obj.getPath().map(x => {
                return [x.lng, x.lat]
                // return lonlatTomercator(x.lng, x.lat)
            }))


        })
        mouseTool.polygon({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'

        });
    }

    const addPolygon = (pathArr) => {
        if (!pathArr) return
        PolygonListArr = pathArr
        PolygonList = []
        // map.value.amap.setZoomAndCenter(12, [pathArr[0][0].lng, pathArr[0][0].lat])
        // map.value.amap.setZoomAndCenter(12, [pathArr[0][0][0], pathArr[0][0][1]])
        for (let i = 0; i < pathArr.length; i++) {
            console.log(pathArr[i])
            let Polygon = new AMap.Polygon({
                path: pathArr[i], // 设置线覆盖物路径
                strokeColor: "#80d8ff",
                strokeOpacity: 1,
                strokeWeight: 6,
                strokeOpacity: 0.2,
                fillColor: '#00b0ff',
                fillOpacity: 0.4,
                map: map.value.amap
            })


            PolygonList.push(Polygon)
        }
    }
    
    const clesoPolygon = () => {
        if (mouseTool) {
            mouseTool.close(true)
            map.value.amap.remove(overlays.value)

        }
        if (PolygonList) {
            PolygonList.map(x => {
                map.value.amap.remove(x)
            })
            PolygonList = []
            PolygonListArr = []

        }
    }

    
    const lonlatTomercator = (x, y) => {
        let lonlat = {
            x,
            y
        }
        var mercator = {
            x: 0,
            y: 0
        };
        var x = lonlat.x * 20037508.34 / 180;
        var y = Math.log(Math.tan((90 + lonlat.y) * Math.PI / 360)) / (Math.PI / 180);
        y = y * 20037508.34 / 180;
        mercator.x = x;
        mercator.y = y;
        return [mercator.x, mercator.y];
    }
    const mercatorTolonlat = (x, y) => {
        let mercator = {
            x,
            y
        }
        var lonlat = {
            x: 0,
            y: 0
        };
        var x = mercator.x / 20037508.34 * 180;
        var y = mercator.y / 20037508.34 * 180;
        y = 180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2);
        lonlat.x = x;
        lonlat.y = y;
        return [lonlat.x, lonlat.y];;
    }



    defineExpose({
        editModel
    })
</script>
<style lang="less" scoped>
    .dmapBox {
        position: relative;
        width: 100%;
        height: 500px;

        .dmap {
            width: 100%;
            height: 100%;

        }

        .seharBox {
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 100;
            display: flex;
            align-content: center;

            div {
                color: #FFF;
            }
        }
    }


    /deep/ .ant-tree-checkbox {
        display: none;
    }

    /deep/ .ant-tree {
        .ant-tree-treenode-switcher-open {
            .ant-tree-child-tree {

                .ant-tree-child-tree {

                    .ant-tree-checkbox {
                        display: inline-block
                    }
                }
            }
        }
    }

    .treewarp {
        border: 1px solid #dedede;
        height: 500px;
        overflow: auto;
    }
</style>